<template>
  <!-- 登录页面的整体盒子 -->
  <div class="login-container">
    <!-- 登录的盒子 -->
    <div class="login-box">
      <!-- 标题的盒子 -->
      <div class="title-box"></div>
      <!-- 登录的表单区域 -->
      <el-form :model="loginForm" :rules="loginRules" ref="loginRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" @keyup.native.enter="login"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="login">登录</el-button>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1-10位的字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      // 兜底校验
      this.$refs.loginRef.validate(async valid => {
        if (!valid) return
        // 发起请求
        // async/await 的写法
        // const { data: res } = await this.$http.post('/api/login', this.loginForm)
        // promise .then 的写法
        this.$http.post('/api/login', this.loginForm)
          .then(({ data: res }) => {
            // console.log(res)
            if (res.code === 0) {
              // 登录成功
              // 提示用户
              this.$message.success(res.message)
              // 将接口返回的 token 存储到本地
              localStorage.setItem('token', res.token)
              // 跳转到后台主页
              this.$router.push('/')
            } else {
              // 登录失败
              // 提示用户
              this.$message.error(res.message)
            }
          }).catch(error => {
            console.log(error)
          })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url('../../assets/images/login_bg.jpg') center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 270px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 20px;
    box-sizing: border-box;

    .title-box {
      height: 60px;
      background: url('../../assets/images/login_title.png') center no-repeat;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
